<template>
  <div>
    <el-form
      ref="deptForm"
      :model="deptForm"
      :rules="deptFormRules"
      label-width="100px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" style="width: 80%" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="deptForm.code" style="width: 80%" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="deptForm.manager"
          placeholder="请选择"
          style="width: 80%"
        >
          <el-option
            v-for="item in employees"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="deptForm.introduce"
          type="textarea"
          style="width: 80%"
        />
      </el-form-item>
      <el-form-item style="padding-left: 25%">
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  name: 'DeptDialog',
  props: {
    // 父级ID
    parentId: {
      type: [String, Number],
      required: true
    },

    // 是否是编辑
    isEdit: {
      type: Boolean,
      default: false
    },

    // 父级格式化好的数据
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验部门编码是否重复
    const validCode = (rules, value, callback) => {
      // 获取所有的部门编码
      let existCodeList = this.originList.map(item => item.code)
      // 判断是否是编辑
      if (this.isEdit) {
        // 如果是编辑的话 先通过filter 筛选排除 当前项 在通过map组装出来
        existCodeList = this.originList.filter(item => item.id !== this.parentId).map(item => item.code)
      }
      //  // 如果存在该对象，则说明编码已经存在，抛出错误 includes 是否包含value  是 : 否
      existCodeList.includes(value) ? callback(new Error(`编码${value}已存在`)) : callback()
    }

    // 同级部门禁止出现重复部门
    const validName = (rules, value, callback) => {
      // 查找同级的分类
      let existNameList = this.originList.filter(item => item.pid === this.parentId).map(item => item.name)
      // 是否是编辑
      if (this.isEdit) {
        // 找到自己对应的对象
        const dept = this.originList.find(item => item.id === this.parentId)
        // 取出父级的 id
        const pid = dept.pid
        // 过滤，筛选出同一级别的数据
        existNameList = this.originList
          .filter(item => item.pid === pid && item.id !== this.parentId)
          .map(item => item.name)
      }
      // 判断最新输入的部门名称是否存在
      existNameList.includes(value) ? callback(new Error(`部门${value}已存在`)) : callback()
    }
    return {
      deptForm: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: [], // 部门管理者 数组
      deptFormRules: { // 规则验证
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门管理者不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 调用获取员工数据方法
    this.getEmployeeData()
    // 调用通过id获取数据方法
    this.getDepartDetail()
  },
  methods: {
    // 添加子部门
    async addDepart() {
      await addDepartments({ ...this.deptForm, pid: this.parentId })
      this.$emit('update-depart')
    },

    // 编辑子部门
    async editDepart() {
      await updateDepartments(this.deptForm)
      this.$emit('update-depart')
    },

    //  通过id获取的数据
    async getDepartDetail() {
      if (this.isEdit) {
        const res = await getDepartDetail(this.parentId)
        // console.log(res)
        this.deptForm = res.data
      }
    },

    // 获取下拉员工数据
    async getEmployeeData() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.employees = res.data
    },

    // 点击确定后
    hSubmit() {
      // 兜底验证
      this.$refs.deptForm.validate(valid => {
        if (valid) {
          // 是否是编辑   ?  是   :   否
          this.isEdit ? this.editDepart() : this.addDepart()
        }
      })
    },

    // 点击取消
    hCancle() {
      this.$emit('close')
    }
  }
}
</script>

<style>
</style>
